Global Variables in Lua

By Hubert Ronald / Leave a response / May 28, 2018

Sometimes they are not declared as local variables and this does to your application have got memory leaked.

Lua keeps all its global variables in a regular table, called the environment. To facilitate such manipulations, Lua stores the environment itself in a global variable _G.

For instance, the following code prints the names of all global variables defined in the current environment:

for _, v in pairs(_G) do print(v) end

And printed outpu is:

--[[
    -----------------------------
    Printed Output
    Global Variables
    -----------------------------
    [Running] lua "/Users/globalVar.lua"

    ipairs
    math
    os
    setmetatable
    dofile
    _VERSION
    error
    xpcall
    _G              -- Notice "_G" is the variable (a table)
                    -- that was used in the "for" loop
    loadstring
    type
    rawlen
    select
    rawset
    coroutine
    require
    module
    next
    arg
    debug
    bit32
    assert
    getmetatable
    string
    pcall
    rawequal
    load
    io
    rawget
    unpack
    print
    package
    loadfile
    collectgarbage
    table
    tostring
    tonumber
    pairs

    -----------------------------
    [Done] exited with code=0 in 0.008 seconds
]]

We can create another global functions, variables and tables and stored in its environment too:

-- create global function and global variable into _G
_G.newFn = function() print("hello world!!!") end
_G.newVar = 3

_G.newFn()          -- Printed Output:  "hello world!!!"
print(_G.new)       -- Printed Output:  3

If instance _G will appear _G.newFn and _G.newVar in the list with all global variable defined previously.

For destroy them simply is necessary to make this:

_G.newFn = nil
_G.new = nil 

It's important to indicate this functionality can able deploy lamdba functions, for more details check this trend





Hubert Ronald

Hiya. I'm Ronald, an Industrial Engineer from Colombia. Hope you enjoyed my ad-free, bullshit-free site. If you liked it, tell someone about it.

Write a response

Your email address will not be published.

RECENT NEWS

Gradient is a small library which offers a clean, minimalistic but powerful API for gradients on mesh canvas when you use it on Gideros Mobile. This script take colors from uiGradients like inspiration.

More information about before here.

SUBSCRIBE

Get monthly updates and free resources.


CONNECT WITH ME